﻿namespace ChangchunPulbicServicesImp.Common;

internal static class APIHelper
{
    /// <summary>
    /// 使用GET方法请求API
    /// </summary>
    /// <typeparam name="ResultType">API返回的对象类型</typeparam>
    /// <param name="httpClient">用于发出请求的HttpClient对象</param>
    /// <param name="uri">目标URI</param>
    /// <param name="expectStatus">期望返回的状态码</param>
    /// <returns></returns>
    internal static async Task<QueryApiResult<ResultType>> GetAsync<ResultType>(HttpClient httpClient, string uri, int expectStatus = 0) where ResultType : APIObjBase
    {
        ///发起请求
        HttpResponseMessage response;
        try
        {
            response = await httpClient.GetAsync(uri);
            //Console.WriteLine(await response.Content.ReadAsStringAsync());
        }

        ///请求发起失败
        catch (Exception e)
        {
            return new QueryApiResult<ResultType>(uri)
            {
                StatusCode = Code.InternalFault,
                Message = "未成功向第三方发起接口请求",
                SourceException = e,
            };
        }

        ///请求发起成功，未正确接到响应
        var json = await response.Content.ReadAsStringAsync();
        if (!response.IsSuccessStatusCode)
            return new QueryApiResult<ResultType>(uri)
            {
                StatusCode = Code.NoResponseFrom3rdPartyAPI,
                Message = "第三方API未正确响应",
                HttpCode = response.StatusCode,
            };

        ///成功接收到响应，查询失败
        var resultObj = JsonConvert.DeserializeObject<ResultType>(json);
        if (resultObj.status != expectStatus)
            return new QueryApiResult<ResultType>(uri)
            {
                StatusCode = Code.BadResultFrom3rdPartyAPI,
                Message = "成功接收到响应，但是第三方API执行出错",
                MessageFrom3rdPartyAPI = $"错误码：{resultObj.status}，详情：{resultObj.message}",
                HttpCode = response.StatusCode,
            };

        ///查询成功
        return new QueryApiResult<ResultType>(uri)
        {
            StatusCode = Code.Succeed,
            Message = "请求成功，正确响应",
            HttpCode = response.StatusCode,
            ResultObject = resultObj
        };
    }
}
